<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>

</body>
<script>
	// 1- Array.prototype中拥有Symbol.iterator属性，类型是函数。
	// 2- Symbol.iterator函数返回的是一个对象，对象拥有属性next,next是一个函数
	// 3- next函数返回的是一个对象，对象中拥有value,done
	// let arr = [1,2,3,4];
	// // console.log(arr[Symbol.iterator]);// ƒ values() { [native code] }
	// const result = arr[Symbol.iterator]();
	// // console.log(result);// Iterator{next:f}
	// console.log(result.next());//{value: 1, done: false}
	// console.log(result.next());//{value: 2, done: false}
	// console.log(result.next());//{value: 3, done: false}
	// console.log(result.next());//{value: 4, done: false}
	// console.log(result.next());//{value: undefined, done: true}
	// console.log(result.next());//{value: undefined, done: true}
	
	// 对象拥有iterator
	Object.prototype[Symbol.iterator] = function () {
		// console.log(this);// {a:1,b:2,c:3}
		const keys = Object.keys(this);// ["a","b","c"]
		let index = 0;
		const that = this;
		return {
			next() {
				// let done = true;
				// let value = undefined;
				// if (index !== keys.length) {
				// 	let key = keys[index++];
				// 	value = [key, that[key]];
				// 	done = false;
				// }
				
				// 优化：
				let value =[keys[index],that[keys[index]]];
				let done = index++ >= keys.length;// 3 -->3  // true
				if(done) value = undefined;
				return {
					value,
					done
				}
			}
		}
	};
	let obj = {
		a: 1,
		b: 2,
		c: 3
	}
	const result = obj[Symbol.iterator]();
	console.log(result.next());// {value:[a,1],done:false}
	console.log(result.next());// {value:[b,2],done:false}
	console.log(result.next());// {value:[c,3],done:false}
	console.log(result.next());// {value:undefined,done:true}
	console.log(result.next());// {value:undefined,done:true}
	for(let [key,value] of obj){
		console.log(key,value)
	}
</script>
</html>